package com.atsmart.app.activity;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.exception.BizException;
import com.atsmart.app.model.CommonBody;
import com.atsmart.app.model.MessageInfo;
import com.atsmart.app.model.ResultInfo;
import com.atsmart.app.model.SendMsgInfo;
import com.atsmart.app.sql.MessageSqlHelper;
import com.atsmart.app.utils.PersistentKeyUtil;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.webservice.ServiceAsynTask;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
import com.google.json.Gson;
import com.google.json.JsonParseException;

public class SendMsgActivity extends BaseActivity implements OnClickListener {
	private static final String TAG = SendMsgActivity.class.getName();
	private Button btnSend;
	private EditText editContent;
	private String content;
	private MessageSqlHelper msql = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.send_msg_layout);
		btnSend = (Button) findViewById(R.id.btn_refresh);
		btnSend.setBackgroundResource(R.drawable.btn_send_selector);
		editContent = (EditText) findViewById(R.id.edit_msg_content);
		msql = new MessageSqlHelper();
		msql.open(BizApp.getInstance().getSqlHelper());
		btnSend.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.btn_refresh) {
			content = editContent.getText().toString().trim();
			if (StringUtil.isEmptyOrNull(content)) {
				Toast.makeText(this, "请输入内容", Toast.LENGTH_SHORT).show();
			} else {
				sendData();
				addData();
			}
		}
	}

	private void sendData() {
		showLoading();
		registerLoadStatus(TAG);
		new ServiceAsynTask<ResultInfo>() {

			@Override
			protected ResultInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException ,Exception{
				CommonBody body = new CommonBody();
				body.setCommand(4);
				body.setImsi(BizApp.getInstance().getIMSI());
				body.setVersion(getString(R.string.app_version));
				SendMsgInfo msgInfo = new SendMsgInfo();
				msgInfo.msges = new ArrayList<SendMsgInfo.Wrapper>();
				SendMsgInfo.Wrapper wrapper = new SendMsgInfo.Wrapper();
				wrapper.content = content;
				msgInfo.msges.add(wrapper);
				Gson gson = new Gson();
				return ServiceHelper.getInstance().postData(
						ServiceHost.sendMsgURL(), gson.toJson(body),
						gson.toJson(msgInfo), ResultInfo.class);
			}

			@Override
			protected void runWithResult(ResultInfo result) throws Exception {
				hideLoading();
				dealWithResult(result);
			}

			@Override
			protected void runWithError(ResultInfo result, int iErrorCode)
					throws Exception {
				loadingFailed(TAG, iErrorCode);
				hideLoading();
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
				try{
					sendDataByUrl2();
				}catch (Exception e) {
				}
			}
		}.execute();
	}

	private void sendDataByUrl2() {
		showLoading();
		registerLoadStatus(TAG);
		new ServiceAsynTask<ResultInfo>() {

			@Override
			protected ResultInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException ,Exception{
				CommonBody body = new CommonBody();
				body.setCommand(4);
				body.setImsi(BizApp.getInstance().getIMSI());
				body.setVersion(getString(R.string.app_version));
				SendMsgInfo msgInfo = new SendMsgInfo();
				msgInfo.msges = new ArrayList<SendMsgInfo.Wrapper>();
				SendMsgInfo.Wrapper wrapper = new SendMsgInfo.Wrapper();
				wrapper.content = content;
				msgInfo.msges.add(wrapper);
				Gson gson = new Gson();
				return ServiceHelper.getInstance().postData(
						ServiceHost.sendMsgURL(), gson.toJson(body),
						gson.toJson(msgInfo), ResultInfo.class);
			}

			@Override
			protected void runWithResult(ResultInfo result) throws Exception {
				hideLoading();
				dealWithResult(result);
			}

			@Override
			protected void runWithError(ResultInfo result, int iErrorCode)
					throws Exception {
				loadingFailed(TAG, iErrorCode);
				hideLoading();
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
			}
		}.execute();
	}

	
	private void dealWithResult(ResultInfo result) {
		if (result != null && result.result == 0) {
			PrefsUtils.setUserState(String.valueOf(PersistentKeyUtil.NORMAL_USER_STATE));
			Toast.makeText(this, "发送消息成功", Toast.LENGTH_SHORT).show();
			this.finish();
		} else {
			PrefsUtils.setUserState(String.valueOf(PersistentKeyUtil.UN_NORMAL_USER_STATE));
//			Toast.makeText(this, "发送消息失败", Toast.LENGTH_SHORT).show();
			Intent intent = new Intent();
			intent.setClass(SendMsgActivity.this, LoginActivity.class);
			startActivity(intent);
			finish();
		}
	}

	private void addData() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		MessageInfo minfo = new MessageInfo();
		minfo.setContent(content);
		minfo.setDate(sdf.format(new Date()));
		minfo.setType(3);
		minfo.setSender("我");
		msql.addMessageInfo(minfo);
		Toast.makeText(this, "发送消息成功", Toast.LENGTH_SHORT).show();
		this.finish();

	}

	// private void dealWithResult(ResultInfo result) {
	// if (result != null && result.result == 0) {
	// Toast.makeText(this, "发送消息成功", Toast.LENGTH_SHORT).show();
	// this.finish();
	// } else {
	// Toast.makeText(this, "发送消息失败", Toast.LENGTH_SHORT).show();
	// }
	// }
}
